package jrain.fw.cfg.classpath;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.cls.ClassUtils;
import jrain.utils.collection.RDMap;
import jrain.utils.collection.RMap;
import jrain.utils.exception.ServiceException;
import jrain.utils.io.IoUtils;
import jrain.utils.lang.StringUtils;

/**
 * <pre>
 * 作者：489088214@qq.com 
 * 描述： 配置文件解析
 * </pre>
 */
public class CfgClasspathValidateParser implements CfgClasspathParser {

	private static final Logger log = LoggerFactory.getLogger("cfg-classpath-validate");

	@Override
	public Map<String, RMap<String, Object>> parserCfg() {
		Map<String, RMap<String, Object>> rsMap = new HashMap<>();
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		ClassUtils.getFiles("validate", ".validate").forEach(path -> {
			try {
				initFile(classLoader, path, rsMap);
			} catch (Exception e) {
				String msg = "validate parser error,file=%s";
				msg = String.format(msg, path);
				log.error(msg, e);
				throw new ServiceException(msg, e);
			}
		});
		log.info("validate parser finish!,{}", this.getClass().getSimpleName());
		return rsMap;
	}

	@SuppressWarnings({ "unchecked" })
	private static final void initFile(ClassLoader classLoader, String path,
			final Map<String, RMap<String, Object>> rsMap) throws Exception {
		byte fileBytes[] = IoUtils.readStream(classLoader.getResourceAsStream(path));
		String json = new String(fileBytes, "UTF-8");
		log.debug("validate file:{},json:{}", path, json);
		Map<String, Object> dataMap = FwUtils.getJsonService().toMap(json);
		if (dataMap != null) {
			String version = StringUtils.trimNull(dataMap.get("version"));
			if ("1.0".equals(version)) {
				List<Object> list = (List<Object>) dataMap.get("data");
				if (list != null) {
					list.forEach(object -> {
						Map<String, Object> validatMap = (Map<String, Object>) object;
						if (validatMap != null) {
							String key = StringUtils.trimNull(validatMap.get("code"));
							if (!StringUtils.isEmpty(key)) {
								rsMap.put("validate." + key, new RDMap<>(validatMap));
							}
						}
					});
				}
			}
		}

	}

}
